import 'dart:math';
import 'dart:ui';

import 'package:audio_spectrum/audio_spectrum.dart';
import 'package:audio_spectrum_example/secondPage.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:get/get.dart';

import 'MyPainter.dart';

class PlayMp3 extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _PlayMp3State();
}

class _PlayMp3State extends State<PlayMp3> {
  String TAG = 'PlayMp3';

  late AudioSpectrum audioSpectrum;

  late int bands;

  int smoothingFactor = 3;
  late List<double> previousValues;
  int maxConst = 25000;

  double? leftX;

  double? top;

  double? rightX;

  double? barHeight;

  List<double>? fft;

  @override
  void initState() {
    super.initState();

    print('$TAG--------->initState');
    audioSpectrum = AudioSpectrum();
    audioSpectrum.listenMusicSpectrum((onEvent) {
      if (mounted) {
        fft = onEvent;
        setState(() {});
      }
    }, (onError) {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(''),
        ),
        body: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                InkWell(
                  child: const Text('选择文件'),
                  onTap: () async {
                    FilePickerResult? result =
                        await FilePicker.platform.pickFiles();
                    audioSpectrum.getAudioSpectrum(result!.files.first.path!);
                  },
                ),
                TextButton(
                    onPressed: () {
                      audioSpectrum.stopPlayer();
                      // Get.to(SecondPage());
                    },
                    child: const Text('停止播放'))
              ],
            ),
            fft != null
                ? CustomPaint(
                    painter: MyPainter(fft!),
                    size: Size(MediaQuery.of(context).size.width, 300),
                  )
                : SizedBox()
          ],
        ));
  }

  @override
  void dispose() {
    audioSpectrum.stopPlayer();
    super.dispose();
  }
}
